package com.gking.processHarvest.service.Harvest;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gking.processHarvest.common.BaseContext;
import com.gking.processHarvest.common.CustomException;
import com.gking.processHarvest.common.Res;
import com.gking.processHarvest.entity.Example;
import com.gking.processHarvest.entity.Harvest;
import com.gking.processHarvest.entity.Module;
import com.gking.processHarvest.entity.Project;
import com.gking.processHarvest.mapper.HarvestMapper;
import com.gking.processHarvest.service.Example.ExampleService;
import com.gking.processHarvest.service.Module.ModuleService;
import com.gking.processHarvest.service.Project.ProjectService;
import com.gking.processHarvest.utils.CheckStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;


@Service
@Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)//三级缓存解决bean循环注入问题
public class HarvestServiceImpl extends ServiceImpl<HarvestMapper, Harvest> implements HarvestService {

    @Autowired
    private ModuleService moduleService;

    @Autowired
    private ExampleService exampleService;

    @Autowired
    private ProjectService projectService;

    /**
     * 创建收获
     *
     * @param pId  项目id
     * @param mId  模块id
     * @param desc 项目描述
     * @return s
     */
    @Override
    public Res<String> create(String pId, String mId, String desc) {
        if (pId == null || desc == null || desc.equals("")) return Res.error("请将参数补充完整");

        LambdaQueryWrapper<Project> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Project::getId, pId);
        lambdaQueryWrapper.eq(Project::getMasterId, BaseContext.getCurrentId());
        if (projectService.getOne(lambdaQueryWrapper) == null) return Res.error("你没有权限创建此项目的收获");

        Harvest harvest = new Harvest();
        harvest.setProjectId(pId);
        harvest.setDescription(desc);

        if (mId != null && !mId.equals("")) {

            //查看模块是否已经存在
            CheckStatus<Module> checkStatus = new CheckStatus<>();
            LambdaQueryWrapper<Module> wrapper = checkStatus.checkIsDelete(
                    mId, Module::getId,
                    Module::getMasterId, Module::getIsDelete);

            Module module = moduleService.getOne(wrapper);
            if (module == null) return Res.error("创建失败，模块信息错误");

            harvest.setModuleId(mId);
            harvest.setModuleName(module.getName());
        }

        this.save(harvest);

        return Res.success("创建成功！");
    }


    /**
     * 删除收获exampleService
     *
     * @param id 收获id
     * @return s
     */
    @Override
    @Transactional
    public Res<String> delete(String id) {
        if (id == null) return Res.error("请将参数补充完整");

        //判断是否存在或者已经删除了
        CheckStatus<Harvest> checkStatus = new CheckStatus<>();
        LambdaQueryWrapper<Harvest> queryWrapper = checkStatus.checkIsDelete(
                id, Harvest::getId,
                Harvest::getMasterId, Harvest::getIsDelete);
        if (this.getOne(queryWrapper) == null) return Res.error("该收获不存在，无法删除");

        //进行删除收获
        LambdaUpdateWrapper<Harvest> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Harvest::getId, id);
        updateWrapper.eq(Harvest::getMasterId, BaseContext.getCurrentId());
        updateWrapper.set(Harvest::getIsDelete, 1);
        updateWrapper.set(Harvest::getDeleteTime, LocalDateTime.now());
        this.update(updateWrapper);

        try {
            //将收获下的示例全部删除
            CheckStatus<Example> checkExample = new CheckStatus<>();
            LambdaQueryWrapper<Example> lambdaQueryWrapper = checkExample.checkIsDelete(
                    id, Example::getHarvestId,
                    Example::getMasterId, Example::getIsDelete);
            exampleService.list(lambdaQueryWrapper).forEach(item -> exampleService.delete(item.getId()));

        } catch (Exception e) {
            throw new CustomException("删除收获成功，删除项目下的子模块时出现未知错误！");
        }

        return Res.success("删除收获成功！");
    }


    /**
     * 修改收获描述
     *
     * @param id   收获id
     * @param desc 收获描述
     * @return s
     */
    @Override
    public Res<String> updateDesc(String id, String desc) {
        if (id == null || desc == null) return Res.error("请将参数补充完整！");

        //判断是否存在或者已经删除了
        CheckStatus<Harvest> checkStatus = new CheckStatus<>();
        LambdaQueryWrapper<Harvest> queryWrapper = checkStatus.checkIsDelete(
                id, Harvest::getId,
                Harvest::getMasterId, Harvest::getIsDelete);
        if (this.getOne(queryWrapper) == null) return Res.error("该收获不存在，无法修改");

        //进行修改
        LambdaUpdateWrapper<Harvest> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Harvest::getId, id);
        updateWrapper.eq(Harvest::getMasterId, BaseContext.getCurrentId());
        updateWrapper.set(Harvest::getDescription, desc);
        this.update(updateWrapper);

        return Res.success("修改成功！");
    }


    /**
     * 修改收获所属模块
     *
     * @param id  收获id
     * @param mId 模块id
     * @return s
     */
    @Override
    public Res<String> modifyModule(String id, String mId) {
        if (id == null) return Res.error("请将参数补充完整");

        //判断是否存在或者已经删除了
        CheckStatus<Harvest> checkStatus = new CheckStatus<>();
        LambdaQueryWrapper<Harvest> queryWrapper = checkStatus.checkIsDelete(
                id, Harvest::getId,
                Harvest::getMasterId, Harvest::getIsDelete);
        if (this.getOne(queryWrapper) == null) return Res.error("该收获不存在，无法修改");

        if (mId == null || mId.equals("")) {
            LambdaUpdateWrapper<Harvest> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Harvest::getId, id);
            updateWrapper.eq(Harvest::getMasterId, BaseContext.getCurrentId());
            updateWrapper.set(Harvest::getModuleId, "");
            updateWrapper.set(Harvest::getModuleName, "");
            this.update(updateWrapper);
        } else {

            //通过模块id去查询模块相关信息
            CheckStatus<Module> checkStatus2 = new CheckStatus<>();
            LambdaQueryWrapper<Module> wrapper = checkStatus2.checkIsDelete(
                    mId, Module::getId,
                    Module::getMasterId, Module::getIsDelete);
            Module module = moduleService.getOne(wrapper);
            if (module == null) return Res.error("修改模块信息错误");

            //查询无误则更新数据
            LambdaUpdateWrapper<Harvest> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Harvest::getId, id);
            updateWrapper.eq(Harvest::getMasterId, BaseContext.getCurrentId());
            updateWrapper.set(Harvest::getModuleId, mId);
            updateWrapper.set(Harvest::getModuleName, module.getName());
            this.update(updateWrapper);
        }

        return Res.success("修改收获模块成功！");
    }


    /**
     * 分页获取收获
     *
     * @param projectId 项目id
     * @param page      分页页码
     * @param pageSize  分页大小
     * @return s
     */
    @Override
    public Res<Page> getPageHarvestList(String projectId, Integer page, Integer pageSize) {
        LambdaQueryWrapper<Harvest> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Harvest::getMasterId, BaseContext.getCurrentId());
        queryWrapper.eq(Harvest::getProjectId, projectId);
        queryWrapper.eq(Harvest::getIsDelete, 0);
        queryWrapper.orderByDesc(Harvest::getCreateTime);

        Page<Harvest> pageInfo = new Page<>(page, pageSize);
        Page<Harvest> pageData = this.page(pageInfo, queryWrapper);

        return Res.success("分页获取收获成功！", pageData);
    }


    /**
     * 获取收获详情
     *
     * @param harvestId 收获id
     * @return s
     */
    @Override
    public Res<Harvest> getHarvestDetail(String harvestId) {

        //判断收获存不存在
        CheckStatus<Harvest> checkStatus2 = new CheckStatus<>();
        LambdaQueryWrapper<Harvest> queryWrapper = checkStatus2.checkIsDelete(
                harvestId, Harvest::getId,
                Harvest::getMasterId, Harvest::getIsDelete);
        Harvest harvestData = this.getOne(queryWrapper);
        if (harvestData == null) return Res.error("收获不存在，获取失败！");

        return Res.success("获取成功！", harvestData);
    }


    /**
     * 获取收获示例列表
     *
     * @param harvestId 收获id
     * @return s
     */
    @Override
    public Res<List<Example>> getHarvestExamples(String harvestId) {

        //判断收获存不存在
        CheckStatus<Harvest> checkStatus1 = new CheckStatus<>();
        LambdaQueryWrapper<Harvest> queryWrapper = checkStatus1.checkIsDelete(
                harvestId, Harvest::getId,
                Harvest::getMasterId, Harvest::getIsDelete);
        if (this.getOne(queryWrapper) == null) return Res.error("收获不存在，获取失败！");

        //获取收获下的所有示例
        CheckStatus<Example> checkStatus2 = new CheckStatus<>();
        LambdaQueryWrapper<Example> wrapper = checkStatus2.checkIsDelete(
                harvestId, Example::getHarvestId,
                Example::getMasterId, Example::getIsDelete);
        List<Example> list = exampleService.list(wrapper);

        return Res.success("获取成功！", list);
    }
}
